#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "comm/mqtt.h"
#include "3rd/sock/msocket.h"

#define SIMPLE_MQTT_CLIENT_ID "smqtt_ji9v0sa"
#define SIMPLE_MQTT_USERNAME "localhost_c"
#define SIMPLE_MQTT_PASSWORD "123456"
#define SIMPLE_MQTT_KEEPALIVE 100

#define SIMPLE_MQTT_SERVER_IPV4 "127.0.0.1"
#define SIMPLE_MQTT_SERVER_PORT 1883


// gcc ./sub.c ../comm/mqtt.c ../3rd/sock/msocket.c -I../ -o sub
int main()
{
	if (socket_init() != 0)
	{
		fprintf(stderr, "socket_init() fail!\n");
		exit(1);
	}
	socket_t sock = socket_tcp();
	if (sock == 0)
	{
		fprintf(stderr, "socket_tcp() fail!\n");
		exit(1);
	}
	if (socket_connect_ipv4(sock, SIMPLE_MQTT_SERVER_IPV4, SIMPLE_MQTT_SERVER_PORT) != 0)
	{
		fprintf(stderr, "socket_connect_ipv4() fail!\n");
		exit(1);
	}
	size_t pack_len = 0;
	unsigned char *data = mqtt_connect_packet(
		SIMPLE_MQTT_CLIENT_ID,
		SIMPLE_MQTT_USERNAME,
		SIMPLE_MQTT_PASSWORD,
		SIMPLE_MQTT_KEEPALIVE,
		1,
		&pack_len);
	
	socket_send(sock, data, pack_len, 0);
	free(data);
	uint8_t recv_buf[8102] = { 0 };
	socket_recv(sock, recv_buf, mqtt_connack_packet_len,0);
	if (strncmp(mqtt_connack_packet, recv_buf,mqtt_connack_packet_len) == 0)
	{
		printf("connect suf!\n");
	}
	else
	{
		goto fail0;
	}
	memset(recv_buf, 0, sizeof(recv_buf));
	u16 seq = 30;
	u8 *topics[] = { "test","en","ch" };
	u8 qoss[] = { 2,0,1 };
	data = mqtt_subscribe_packet(topics, qoss, sizeof(topics)/sizeof(u8*), &pack_len, seq);
	socket_send(sock, data, pack_len, 0);
	free(data);
	char * suback_buf = mqtt_suback_packet(qoss, sizeof(topics)/sizeof(u8*), &pack_len, seq);
	socket_recv(sock, recv_buf, pack_len, 0);
	if (strncmp(suback_buf, recv_buf, pack_len) == 0)
	{
		printf("sub suf!\n");
		data = mqtt_unsubscribe_packet(topics, sizeof(topics) / sizeof(u8 *), &pack_len, seq);
		socket_send(sock, data, pack_len, 0);
		free(data);
		char unsubact_buf[mqtt_unsuback_packet_len] = { 0 };
		mqtt_unsuback_packet(unsubact_buf, seq);
		socket_recv(sock, recv_buf, mqtt_unsuback_packet_len, 0);
		if (strncmp(recv_buf, unsubact_buf, mqtt_unsuback_packet_len) == 0)
		{
			printf("unsub suf!\n");
		}
		else
		{
			goto fail1;
		}
	}
	else
	{
		goto fail1;
	}
fail1:
	free(suback_buf);
	socket_send(sock, mqtt_disconnect_packet, mqtt_disconnect_packet_len, 0);
fail0:
	socket_close(sock);
	socket_cleanup();
	return 0;
}